#include "VoiceIntercom.h"
#include<PluginException.h>
//#include <mutex>
#include"HikDVRSDKErrorMsg.h"

//typedef void(CALLBACK* fVoiceDataCallBack)(
//	LONG     lVoiceComHandle,
//	char* pRecvDataBuffer,
//	DWORD    dwBufSize,
//	BYTE     byAudioFlag,
//	void* pUser
//	);


string VoiceIntercom::lastErrorMsg;
RESULT_CODE VoiceIntercom::startVoiceCom(CameraDevInfo devInfo, long voiceChannel, VoiceDataType dataType, long& talkHandle, fVoiceDataCallBack pFunc, void* pUser)
{
	try
	{
		CDevice* pDev = getDevice(devInfo);
		string resultMsg;
		if (pDev == nullptr) {
			return RESULT_CODE::RET_FAILED;
		}
		
		LPNET_DVR_DEVICEINFO_V30 pNetDeviceInfo = (LPNET_DVR_DEVICEINFO_V30)(pDev->m_pDevInfo);

		if (!pNetDeviceInfo) {
			return RESULT_CODE::RET_FAILED;
		}
		DWORD dwVoiceChanNo = 0;
		if (voiceChannel < pNetDeviceInfo->byAudioChanNum)
		{
			dwVoiceChanNo = voiceChannel;
		}
		else
		{
			dwVoiceChanNo = voiceChannel - pNetDeviceInfo->byStartDChan + pNetDeviceInfo->byStartDTalkChan; //Digital voice talk Chan 
		}

		talkHandle = NET_DVR_StartVoiceCom_V30(pDev->m_lLoginID, dwVoiceChanNo, dataType == VoiceDataType::ENCODED ? 0 : 1, pFunc, pUser);
		if (talkHandle == -1) {
			DWORD dwError = NET_DVR_GetLastError();
			throw PluginException(GetDVRNETLastErrorMsg(dwError));
		}
		return RESULT_CODE::RET_OK;
	}
	catch (PluginException& eException) {
		VoiceIntercom::lastErrorMsg = eException.GetExcepInfo();
		return RESULT_CODE::RET_FAILED;
	}
	return RESULT_CODE::RET_OK;
}

RESULT_CODE VoiceIntercom::stopVoiceCom(long talkHandle)
{
	if (NET_DVR_StopVoiceCom(talkHandle)) {
		return RESULT_CODE::RET_OK;
		
	}
	else {
		DWORD dwError = NET_DVR_GetLastError();
		VoiceIntercom::lastErrorMsg = GetDVRNETLastErrorMsg(dwError);
		return RESULT_CODE::RET_FAILED;
	}
}


CDevice* VoiceIntercom::getDevice(CameraDevInfo devInfo)
{
	CDevice* pDev = CDeviceManage::getInstance()->GetDeviceByUUID(devInfo.devId);
	string resultMsg;
	if (pDev == nullptr) {
		DeviceInfo contentDeviceInfo;
		sprintf_s(contentDeviceInfo.strUUID, devInfo.devId.c_str());
		sprintf_s(contentDeviceInfo.strIP, devInfo.devIp.c_str());
		contentDeviceInfo.nPort = devInfo.devPort;
		sprintf_s(contentDeviceInfo.strUserName, devInfo.devUsername.c_str());
		sprintf_s(contentDeviceInfo.strPassword, devInfo.devPassword.c_str());
		pDev = CDeviceManage::getInstance()->GetDeviceByDevInfo(contentDeviceInfo, resultMsg, true);
	}
	return pDev;
}
